<?php

App::uses('AppController', 'Controller');

/**
 * Articles Controller
 *
 * @property Article $Article
 */
class ArticlesController extends AppController {

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('*');
    }

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        $this->Article->recursive = 0;
        $this->set('articles', $this->paginate());
    }

    /**
     * view method
     *
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        $this->Article->id = $id;
        if (!$this->Article->exists()) {
            throw new NotFoundException(__('Invalid article'));
        }
        $this->set('article', $this->Article->read(null, $id));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add() {
        if ($this->request->is('post')) {
            $this->Article->create();
            if ($this->Article->save($this->request->data)) {
                $this->Session->setFlash(__('The article has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The article could not be saved. Please, try again.'));
            }
        }
        $users = $this->Article->User->find('list');
        $this->set(compact('users'));
    }

    /**
     * edit method
     *
     * @param string $id
     * @return void
     */
    public function edit($id = null) {
        $this->Article->id = $id;
        if (!$this->Article->exists()) {
            throw new NotFoundException(__('Invalid article'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Article->save($this->request->data)) {
                $this->Session->setFlash(__('The article has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The article could not be saved. Please, try again.'));
            }
        } else {
            $this->request->data = $this->Article->read(null, $id);
        }
        $users = $this->Article->User->find('list');
        $this->set(compact('users'));
    }

    /**
     * delete method
     *
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
        /*
          if (!$this->request->is('post')) {
          throw new MethodNotAllowedException();
          }
          $this->Article->id = $id;
          if (!$this->Article->exists()) {
          throw new NotFoundException(__('Invalid article'));
          }
          if ($this->Article->delete()) {
          $this->Session->setFlash(__('Article deleted'));
          $this->redirect(array('action' => 'index'));
          }
          $this->Session->setFlash(__('Article was not deleted'));
          $this->redirect(array('action' => 'index')); */
    }

    /**
     * admin_index method
     *
     * @return void
     */
    public function admin_index() {
        $this->Article->recursive = 0;
        $this->paginate = array(
          'conditions' => array(
              'Article.type' => ARTICLE_TYPE_ARTICLE
          ),
            'order' => array(
                'Article.id' => 'DESC'
                )
        );
        $this->set('articles', $this->paginate());
    }

    /**
     * admin_view method
     *
     * @param string $id
     * @return void
     */
    public function admin_view($id = null) {
        $this->Article->id = $id;
        if (!$this->Article->exists()) {
            throw new NotFoundException(__('Invalid article'));
        }
        $this->set('article', $this->Article->read(null, $id));
    }

    /**
     * admin_add method
     *
     * @return void
     */
    public function admin_add() {
        $this->setPageTitle(__('Add New Article'));
        if ($this->request->is('post')) {

            if ($this->request->data['Article']['filename']['size'] == 0 || $this->request->data['Article']['filename']['error'] == 4) {
                $this->Session->setFlash(__('The fine name is not empty'), 'default', array('class' => 'error'));
                //$this->set('article', $this->request->data);
                //$this->redirect(array('action' => 'add', 'admin' => true));
            } else {
                $this->request->data['Article']['user_id'] = $this->Auth->user('id');

                $mediaData['Media'] = array(
                    'article_id' => '2222222222',
                    'filename' => $this->request->data['Article']['filename'],
                    'user_id' => $this->Auth->user('id')
                );
                // Save 
                $mediaId = $this->Article->Media->saveMedia($mediaData);
                if ($mediaId) {
                    $this->Article->create();
                    if ($this->Article->save($this->request->data)) {
                        $this->Session->setFlash(__('The article has been saved'));
                        $this->Article->Media->updateArticleId($mediaId, $this->Article->id);
                        $this->redirect(array('action' => 'index'));
                    } else {
                        $this->Session->setFlash(__('The article could not be saved. Please, try again.'),'default', array('class' => 'error'));
                    }
                } else {
                    $this->Session->setFlash(__('Wrong file format. Please, try again.'), 'defaul', array('class' => 'error'));
                }
            }
        }
        $users = $this->Article->User->find('list');
        $this->set(compact('users'));
    }

    /**
     * admin_edit method
     *
     * @param string $id
     * @return void
     */
    public function admin_edit($id = null) {
        $this->Article->id = $id;
        if (!$this->Article->exists()) {
            throw new NotFoundException(__('Invalid article'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Article->save($this->request->data)) {
                $this->Session->setFlash(__('The article has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The article could not be saved. Please, try again.'),  'default', array('class' => 'error'));
            }
        } else {
            $this->request->data = $this->Article->read(null, $id);
        }
        $users = $this->Article->User->find('list');
        $this->set(compact('users'));
    }

    /**
     * admin_sendNewsletter method
     * 
     */
    public function admin_sendNewsletter($id) {
        $this->setPageTitle(__('Send newslatter'));     
        $articles = $this->Article->find('first', array(
            'conditions' => array('Article.id' => $id),            
            'recursive' => 1,
            'contain' => array('Media')
        ));
        //$users = $this->Article->User->getSubscribers();
        //pr($users); die();
        if ($this->request->is('post')) {
            $users = $this->Article->User->getSubscribers();
            
            $this->Article->id = $this->request->data['Article']['id'];
            $this->Article->saveField('status', ARTICLE_STATUS_SENT);
            $this->Article->saveField('send_date', date('Y-m-d h:i:s'));
            
            $this->Session->setFlash(__('Article has been sent.'));
            
            $title = $this->data['Article']['title'];
            $msg = $this->data['Article']['message'];
            if (strlen($title) == 0) {
               $title = __('True News World Newsletter on %s', date('Y-m-d'));
            }
            
            $defaults = array(
            'from' => Configure::read('App.defaultEmail'),
            'subject' =>  $title,
            'template' => 'send_article',
            'layout' => 'default');
                        
            //$options = array_merge($defaults, $options);
            $options = $defaults;
            $Email = $this->_getMailInstance();
            foreach($users as $user){
                
                $Email->to($user['User']['email'])
                        ->from($options['from'])
                        ->subject($options['subject'])
                        ->template($options['template'], $options['layout'])
                        ->viewVars(array(
                            'model' => $this->modelClass,
                            'user' => $user,
                            'mid' => $articles['Media'][0]['id'],
                            'title' => $title,
                            'msg' => $msg
                            ))
                        ->send();
            
                // Send Log
                $sendLog = array(
                    'SendLog' => array(
                        'send_by' => $this->Auth->user('id'),
                        'user_id' => $user['User']['id'],
                        'article_id' => $id,
                        'send_date' => date('Y-m-d H:i:s'),
                        'title' => $title,
                        'description' => $msg
                        )
                );
                $this->Article->SendLog->create();
                $this->Article->SendLog->save($sendLog);
            }
            $this->redirect(array('action' => 'index'));
        }
        $this->set('title' , $articles['Article']['title']);
        $this->set('id', $id);                
    }
    protected function _getMailInstance() {
        App::uses('CakeEmail', 'Network/Email');
        return new CakeEmail();
    }
    /**
     * admin_delete method
     *
     * @param string $id
     * @return void
     */
    public function admin_delete($id = null) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Article->id = $id;
        if (!$this->Article->exists()) {
            throw new NotFoundException(__('Invalid article'));
        }
        if ($this->Article->delete()) {
            $this->Session->setFlash(__('Article deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Article was not deleted'), 'default', array('class' => 'error'));
        $this->redirect(array('action' => 'index'));
    }
    /**
     * admin_sample_article method
     *
     * @param string $id
     * @return void
     */
    public function admin_sampleArticles() {
        $this->Article->recursive = 0;
        $this->paginate = array(
          'conditions' => array(
              'Article.type' => ARTICLE_TYPE_SAMPLE
          ),
            'order' => array(
                'Article.id' => 'DESC'
                )
        );
        $this->set('articles', $this->paginate());
    }
    /**
     * admin_view method
     *
     * @param string $id
     * @return void
     */
    public function admin_viewSampleArticles($id = null) {
        $this->Article->id = $id;
        if (!$this->Article->exists()) {
            throw new NotFoundException(__('Invalid article'));
        }
        $this->set('article', $this->Article->read(null, $id));
    }

    /**
     * admin_add method
     *
     * @return void
     */
    public function admin_addSampleArticles() {
        $this->setPageTitle(__('Add New Sample Article'));
        if ($this->request->is('post')) {
            
            if ($this->request->data['Article']['filename']['size'] == 0 || $this->request->data['Article']['filename']['error'] == 4) {
                $this->Session->setFlash(__('The file name is not empty'));
                //$this->set('article', $this->request->data);
                //$this->redirect(array('action' => 'add', 'admin' => true));
            } else  {
                if($this->Auth->user('id')){
                    $this->request->data['Article']['user_id'] = $this->Auth->user('id');               
                    $this->Article->create();
                    if ($this->Article->save($this->request->data)) {
                        $mediaData['Media'] = array (
                            'article_id' => $this->Article->id,
                            'filename' => $this->request->data['Article']['filename'],
                            'user_id' => $this->Auth->user('id')
                        );
                        // Save 
                       $this->Article->Media->saveMedia($mediaData);

                        $this->Session->setFlash(__('The article has been saved'));
                        $this->redirect(array('action' => 'sampleArticles'));
                    } else {
                        $this->Session->setFlash(__('The article could not be saved. Please, try again.'), 'default', array('class' => 'error'));
                    }
                }else{
                    $this->Session->setFlash(__('Please login before add sample article'), 'default', array('class' => 'error'));
                    $this->redirect(array('controller' => 'users', 'action' => 'login'));
                }
           }
        }
        $users = $this->Article->User->find('list');
        $this->set(compact('users'));
    }

    /**
     * admin_edit method
     *
     * @param string $id
     * @return void
     */
    public function admin_editSampleArticles($id = null) {//pr($this->data);die();
        $this->setPageTitle("Edit Sample Article");
        $this->Article->id = $id;
        if (!$this->Article->exists()) {
            throw new NotFoundException(__('Invalid article'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if($this->Auth->user(id)){
                if ($this->Article->save($this->request->data)) {
                     if ($this->request->data['Article']['filename']['size'] != 0) {
                        $mediaData['Media'] = array (
                                'id' => $this->request->data['Media']['id'],
                                'article_id' => $this->Article->id,
                                'filename' => $this->request->data['Article']['filename'],
                                'user_id' => $this->Auth->user('id')
                            );
                            // Save 
                           $this->Article->Media->saveMedia($mediaData);
                    }
                    $this->Session->setFlash(__('The sample article has been saved'));
                    $this->redirect(array('action' => 'sampleArticles'));
                } else {
                    $this->Session->setFlash(__('The sample article could not be saved. Please, try again.'), 'default', array('class' => 'error'));
                }
            }else{
                    $this->Session->setFlash(__('Please login before edit sample article'), 'default', array('class' => 'error'));
                    $this->redirect(array('controller' => 'users', 'action' => 'login'));
                }
        } else {
            $this->request->data = $this->Article->read(null, $id);
            //pr($this->request->data);die();
        }
        $users = $this->Article->User->find('list');
        $this->set(compact('users'));
    }
    /**
     * admin_delete_sample_article method
     *
     * @param string $id
     * @return void
     */
    public function admin_deleteSampleArticles($id = null) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Article->id = $id;
        if (!$this->Article->exists()) {
            throw new NotFoundException(__('Invalid sample article'));
        }
                
        if ($this->Article->delete()) {
            $medie_tmp = $this->Article->Media->find('first',array(
                'conditions' => array(
                    'article_id' => $id
                    ),
                'recursive' => -1
                )                
            );
            if($this->Article->Media->deleteAll(array('article_id' => $id))){               
                unlink(WWW_ROOT . $medie_tmp['Media']['dir'] . DS . $medie_tmp['Media']['filename']);
            }
            $this->Session->setFlash(__('Sample Article deleted'));
            $this->redirect(array('action' => 'sampleArticles'));
        }
        $this->Session->setFlash(__('Sample Article was not deleted'), 'default', array('class' => 'error'));
        $this->redirect(array('action' => 'sampleArticles'));
    }
    
    /**
     * admin_add method
     *
     * @return void
     */
    public function admin_testimonial() {
        $this->setPageTitle(__('Testimonial'));
        $this->Article->recursive = 0;
        $this->paginate = array(
          'conditions' => array(
              'Article.type' => ARTICLE_TYPE_TESTIMONIAL
          ),
            'order' => array(
                'Article.id' => 'DESC'
                )
        );
        $this->set('articles', $this->paginate());
    }
    /**
     * admin_add method
     *
     * @return void
     */
    public function admin_addTestimonial() {
        $this->setPageTitle(__('Add New Testimonial'));
        if ($this->request->is('post')) {
                        
                if($this->Auth->user('id')){
                    $this->request->data['Article']['user_id'] = $this->Auth->user('id');               
                    $this->Article->create();
                    if ($this->Article->save($this->request->data)) {                        
                        $this->Session->setFlash(__('The testimonial has been saved'));
                        $this->redirect(array('action' => 'testimonial'));
                    } else {
                        $this->Session->setFlash(__('The testimonial could not be saved. Please, try again.'), 'default', array('class' => 'error'));
                    }
                }else{
                    $this->Session->setFlash(__('Please login before add testimonial'), 'default', array('class' => 'error'));
                    $this->redirect(array('controller' => 'users', 'action' => 'login'));
                }           
        }
        $users = $this->Article->User->find('list');
        $this->set(compact('users'));
    }
    public function admin_viewTestimonial($id = null) {
        $this->Article->id = $id;
        if (!$this->Article->exists()) {
            throw new NotFoundException(__('Invalid article'));
        }
        $this->set('article', $this->Article->read(null, $id));
    }
    public function admin_editTestimonial($id = null) {
        $this->setPageTitle("Edit Testimonial");
        $this->Article->id = $id;
        if (!$this->Article->exists()) {
            throw new NotFoundException(__('Invalid article'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Article->save($this->request->data)) {                 
                $this->Session->setFlash(__('The testimonial has been saved'));
                $this->redirect(array('action' => 'testimonial'));
            } else {
                $this->Session->setFlash(__('The testimonial could not be saved. Please, try again.'), 'default', array('class' => 'error'));
            }
        } else {
            $this->request->data = $this->Article->read(null, $id);
            //pr($this->request->data);die();
        }
        $users = $this->Article->User->find('list');
        $this->set(compact('users'));
    }
    public function admin_deleteTestimonial($id = null) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Article->id = $id;
        if (!$this->Article->exists()) {
            throw new NotFoundException(__('Invalid sample article'));
        }
                
        if ($this->Article->delete()) {            
            $this->Session->setFlash(__('Testimonial deleted'));
            $this->redirect(array('action' => 'testimonial'));
        }
        $this->Session->setFlash(__('Testimonial was not deleted'), 'default', array('class' => 'error'));
        $this->redirect(array('action' => 'testimonial'));
    }
    /**
     * latest method
     *
     * @return void
     */
    public function latest() {
        $this->setPageTitle(__('Latest Article'));
        $this->Article->recursive = 1;
        $this->paginate = array(
          'conditions' => array(
              'Article.type' => ARTICLE_TYPE_SAMPLE
          ),
            'order' => array(
                'Article.id' => 'DESC'
                ),
            'limit' => 10
        );
        $this->set('articles', $this->paginate());
    }
    public function sample() {
        $this->setPageTitle(__('Sample Article'));
        $this->Article->recursive = 1;
        $this->paginate = array(
          'conditions' => array(
              'Article.type' => ARTICLE_TYPE_SAMPLE
          ),
            'order' => array(
                'Article.id' => 'DESC'
                ),
            'limit' => 10
        );
        $this->set('articles', $this->paginate());
    }
    public function testimony(){
            if(!empty($this->data)){
                //if($this->Auth->user('id')){                                             
                    $arr = array(
                            'Article' => array(
                                'type' => ARTICLE_TYPE_TESTIMONIAL,
                                //'user_id' => $this->Auth->user('id'),
                                'content' => $this->data['Page']['testimony'],
                                'status' => 0
                            )
                        );                    
                    $this->Article->create();//pr($arr);die();
                    if($this->Article->save($arr)){
                        $this->Session->setFlash('Submit succesfull');
                        $this->redirect('testimony');
                    }
//                }else{
//                    $this->redirect(array('controller' => 'users', 'action' => 'login'));
//                }
            }else{                           
                $testimonies = $this->Article->find('all',array(
                        'conditions' => array(
                            'Article.type' => ARTICLE_TYPE_TESTIMONIAL,
                            'Article.status' => 1
                            ),
                        'contain' => array('User'),
                        'order' => array(
                            'Article.id' => 'DESC'
                            )
                    
                    ));
//                if($this->Auth->user('id')){
//                    $testimonies2 = $this->Article->find('all',array(
//                            'conditions' => array(
//                                'Article.type' => ARTICLE_TYPE_TESTIMONIAL,
//                                'Article.status' => 0,
//                                'Article.user_id' => $this->Auth->user('id')
//                                ),
//                            'contain' => array('User'),
//                            'order' => array(
//                                'Article.id' => 'DESC'
//                                )
//                        ));
//                    $testimonies = array_merge($testimonies,$testimonies2);
//                    $this->set('users', $this->Auth->user());
//                }
                //$this->set('testimonies',$testimonies);
                $this->paginate = array(
                        'conditions' => array(
                            'Article.type' => ARTICLE_TYPE_TESTIMONIAL,
                            'Article.status' => 1
                            ),
                        'contain' => array('User'),
                        'order' => array(
                            'Article.id' => 'DESC'
                            )
                    
                    );
                $this->set('testimonies',$this->paginate());
            }
    }
}
